#include "timer.h"

static uint8_t timer_flag = 0;

static void Timer_NVIC_Config(void)
{
    NVIC_InitTypeDef NVIC_InitStructure;

    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);

    NVIC_InitStructure.NVIC_IRQChannel = TIMER_IRQN;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;

    NVIC_Init(&NVIC_InitStructure);
}

void Timer_Init(void)
{
    TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;

    RCC_APB1PeriphClockCmd(TIMER_CLK, ENABLE);

    TIM_TimeBaseStructure.TIM_Prescaler = 7200 - 1;
    TIM_TimeBaseStructure.TIM_Period = 10000 - 1;
    TIM_TimeBaseInit(TIMER, &TIM_TimeBaseStructure);

    TIM_ClearFlag(TIMER, TIM_FLAG_Update);

    TIM_ITConfig(TIMER, TIM_IT_Update, ENABLE);

    Timer_NVIC_Config();

    TIM_Cmd(TIMER, ENABLE);
}

uint8_t Timer_ReadFlag(void)
{
    return timer_flag;
}

void TIMER_IRQHANDLER(void)
{
    if (TIM_GetITStatus(TIMER, TIM_IT_Update) != RESET)
    {
        timer_flag = !timer_flag;

        TIM_ClearITPendingBit(TIMER, TIM_IT_Update);
    }
}